def registry = "registry-vpc.cn-hangzhou.aliyuncs.com"
def namespace = ""
def username = ""
def password = ""
def k8s_namespace = ''
def k8s_app_backend = ""
def k8s_app_celery = ""
podTemplate(containers: [
    containerTemplate(name: 'git', image: 'registry.cn-hangzhou.aliyuncs.com/test/jenkins-slave:git-alpine', ttyEnabled: true, command: 'cat'),
    containerTemplate(name: 'docker',ttyEnabled: true,image: 'registry-vpc.cn-hangzhou.aliyuncs.com/test/jenkins-slave:docker'),
    containerTemplate(name: 'kubectl', image: 'registry.cn-hangzhou.aliyuncs.com/test/jenkins-slave:kubectl', ttyEnabled: true, command: 'cat')
  ],
  volumes: [
           hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'),
           hostPathVolume(hostPath: '/opt/k8s.yaml', mountPath: '/opt/k8s.yaml'),
           hostPathVolume(hostPath: '/root/.kube', mountPath: '/root/.kube')
            ]
  ){
    node(POD_LABEL) {
        stage('git') {
            container('git') {
                git credentialsId: 'xxxx', url: 'xxxx.git'
            }
        }
        stage('Docker Build') {
            container('docker') {
                script {
                    def mytag = sh returnStdout: true, script: 'git describe --always --tag'
                    def image_backend = "${k8s_app_backend}:${mytag}".minus("\n")
                    sh """
                        cp /opt/k8s.yaml/Dockerfile .
                        docker login -u ${username} -p \"${password}\" ${registry}
                        docker build -t "${registry}/${namespace}/${image_backend}" .
                        docker push ${registry}/${namespace}/${image_backend}
                        docker rmi ${registry}/${namespace}/${image_backend}
                    """
                }
            }
        }
        stage('Deploy to k8s') {
            container('kubectl') {
                script{
                    def mytag = sh returnStdout: true, script: 'git describe --always --tag'
                    def image_backend = "${k8s_app_backend}:${mytag}".minus("\n")
                    sh """
                        cp /opt/k8s.yaml/template/deploy_template.yaml ./cashier-deploy.yaml
                        cp /opt/k8s.yaml/template/celery_template.yaml ./cashier-celery.yaml
                        sed -i 's#cashier_backend:latest#${registry}/${namespace}/${image_backend}#' deploy.yaml
                        kubectl apply -f deploy.yaml
                    """
                }
            }
        }
        stage('Container Healthy Check') {
            container('kubectl') {
                sh "/opt/k8s.yaml/k8s-healthycheck.sh ${k8s_app_backend} ${k8s_namespace}"
                sh "/opt/k8s.yaml/k8s-healthycheck.sh ${k8s_app_celery} ${k8s_namespace}"
            }
        }
    }
}
